package logic

import (
	"context"
	"encoding/json"
	"shopping/model/mysql"
	"shopping/model/redis"
	"shopping/shoprpc/internal/svc"
	"shopping/shoprpc/shoprpc"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *shoprpc.ProductListRequest) (*shoprpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	size := in.Size
	if page <= 0 {
		page = 1
	}
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size

	var products []mysql.Product
	itoa := strconv.Itoa(int(offset))
	get := redis.Client.Get("productList" + itoa)
	if get.Val() == "" {
		mysql.DB.Debug().Model(&mysql.Product{}).Offset(int(offset)).Limit(int(size)).Where("name like ?", "%"+in.Name+"%").Order("price desc").Find(&products)

		marshal, _ := json.Marshal(&products)

		redis.Client.Set("productList"+itoa, marshal, time.Hour*24)
	} else {
		json.Unmarshal([]byte(get.Val()), &products)
	}

	var Lists []*shoprpc.ProductList
	for _, m := range products {
		List := &shoprpc.ProductList{
			Name:  m.Name,
			Img:   m.Img,
			Price: float32(m.Price),
			Title: m.Title,
			Area:  m.Area,
		}
		Lists = append(Lists, List)
	}

	return &shoprpc.ProductListResponse{List: Lists}, nil
}
